<template>
    <div class="app-container">
        <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">

            <el-form-item label="药店名称" prop="placePointName">
                <el-input v-model="queryParams.placePointName" placeholder="请输入内容" clearable style="width: 240px"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="药品名称" prop="goodsName">
                <el-input v-model="queryParams.goodsName" placeholder="请输入内容" clearable style="width: 240px"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择状态">
                    <el-option v-for="dict in dict.type.sys_give_state" :key="dict.value" :label="dict.label"
                        :value="dict.value"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="el-icon-search" class="add"
                    @click="handleQuery">查询</el-button>
                <el-button icon="el-icon-refresh"  class="delBtn" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button v-hasPermi="['bus:donation:add']" type="primary" plain icon="el-icon-plus" class="add" @click="handleAdd">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button v-hasPermi="['bus:donation:remove']" type="primary" plain icon="el-icon-delete" class="delBtn"
                    @click="handleDelete" :disabled="multiple">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button v-hasPermi="['bus:donation:importData']" type="info" plain icon="el-icon-upload2" @click="handleImport">导入</el-button>
            </el-col>
            <right-toolbar :show-search.sync="showSearch" @queryTable="getListData" />
        </el-row>
        <el-table ref="table" :key="tableKey" v-loading="loading" :data="roleList" style="margin-top: 20px"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="ID" prop="id" />
            <el-table-column label="药店ID" prop="placePointId" />
            <el-table-column label="怡年货品ID" prop="goodsId" />
            <el-table-column label="状态" align="center">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.sys_give_state" :value="scope.row.status" />
                </template>
            </el-table-column>
            <el-table-column label="药品名称" prop="goodsName" />
            <el-table-column label="规格" prop="goodsType" />
            <el-table-column label="厂家" prop="factoryName" />
            <el-table-column label="药店名称" prop="placePointName" />
            <el-table-column label="门店电话" prop="tel" />
            <el-table-column label="门店地址" prop="address" />
            <el-table-column label="基金会/项目办" prop="foundation" />
            <el-table-column label="援助项目" prop="aidProject" />
            <el-table-column label="援助项目链接" prop="aidProjectUrl" />
            <el-table-column label="单价" prop="unitPrice" />
            <el-table-column label="门店操作系统网址" prop="operateUrl" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button v-hasPermi="['bus:donation:edit']" type="text" class="btnText" @click="handleUpdate(scope.row)">编辑</el-button>
                    <el-button v-hasPermi="['bus:donation:editState']" type="text" v-if="scope.row.status == 0" class="btnText" @click="handlePutShop(scope.row)">上架</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getListData" />
        <el-dialog :title="title" :visible.sync="open" width="786px" append-to-body>
            <el-form ref="addForm" :model="addForm" :rules="addRules" label-position="top">
                <el-row :gutter="10">
                    <el-col :span="12">
                        <el-form-item label="药店ID" prop="placePointId">
                            <el-input v-model="addForm.placePointId" placeholder="请输入内容" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="怡年货品ID" prop="goodsId">
                            <el-input v-model="addForm.goodsId" placeholder="请输入内容" />
                        </el-form-item>
                    </el-col>
                   
                </el-row>
                <el-row :gutter="10">
                    <el-col :span="12">
                        <el-form-item label="上架状态" prop="status">
                            <el-switch v-model="addForm.status" :active-value="1" :inactive-value="0" active-color="#0052d9" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="药品名称" prop="goodsName">
                            <el-input v-model="addForm.goodsName" placeholder="请输入内容" />
                        </el-form-item>
                    </el-col>
                   
                </el-row>
                <el-row :gutter="10">
                    <el-col :span="12">
                        <el-form-item label="规格" prop="goodsType">
                            <el-input v-model="addForm.goodsType" placeholder="请输入内容" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="厂家" prop="factoryName">
                            <el-input v-model="addForm.factoryName" placeholder="请输入内容" />
                        </el-form-item>
                    </el-col>
                   
                </el-row>
                <el-row :gutter="10">
                    <el-col :span="12">
                        <el-form-item label="药店名称" prop="placePointName">
                            <el-input v-model="addForm.placePointName" placeholder="请输入内容" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="门店电话" prop="tel">
                            <el-input v-model="addForm.tel" placeholder="请输入内容" />
                        </el-form-item>
                    </el-col>
                   
                </el-row>
                <el-row :gutter="10">
                    <el-col :span="12">
                        <el-form-item label="门店地址" prop="address">
                            <el-input v-model="addForm.address" placeholder="请输入内容" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="基金会/项目办" prop="foundation">
                            <el-input v-model="addForm.foundation" placeholder="请输入内容" />
                        </el-form-item>
                    </el-col>
                    
                </el-row>
                <el-row :gutter="10">
                    <el-col :span="12">
                        <el-form-item label="援助项目" prop="aidProject">
                            <el-input v-model="addForm.aidProject" placeholder="请输入内容" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="援助项目链接" prop="aidProjectUrl">
                            <el-input v-model="addForm.aidProjectUrl" placeholder="请输入内容" />
                        </el-form-item>
                    </el-col>
                    
                </el-row>
                <el-row :gutter="10">
                    <el-col :span="12">
                        <el-form-item label="单价" prop="unitPrice">
                            <el-input v-model="addForm.unitPrice" placeholder="请输入内容" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="门店操作系统网址" prop="operateUrl">
                            <el-input v-model="addForm.operateUrl" placeholder="请输入内容" />
                        </el-form-item>
                    </el-col>
                </el-row>
                
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" class="add" @click="submitForm">{{
            addForm.id ? "确认编辑" : "确认添加"
        }}</el-button>
            </div>
            <el-dialog :visible.sync="dialogVisible" :modal="false">
                <el-image :src="dialogImageUrl" :fit="fit"></el-image>
            </el-dialog>
        </el-dialog>

        <!-- 用户导入对话框 -->
        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
            <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                :action="upload.url" :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <!-- <div class="el-upload__tip" slot="tip">
                        <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
                    </div> -->
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                        @click="importTemplate">下载模板</el-link>
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    getList,
    addData,
    editData,
    actionData,
    putShopData
} from "@/api/medicalCharitableManage/give";
import { getToken } from "@/utils/auth";
import { getUserProfile } from "@/api/system/user";
export default {
    name: "Role",
    dicts: ["sys_give_state"],
    data() {
        return {
            fit:'none',
            dialogVisible: false,
            dialogImageUrl: "",
            uploadUrl:
                process.env.VUE_APP_BASE_API + "/common/uploadPc/goodsRegister", // 上传的图片服务器地址
            headers: {
                Authorization: "Bearer " + getToken(),
            },
            // 用户导入参数
            upload: {
                // 是否显示弹出层（用户导入）
                open: false,
                // 弹出层标题（用户导入）
                title: "",
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的用户数据
                updateSupport: 0,
                // 设置上传的请求头部
                headers: { Authorization: "Bearer " + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + "/bus/donation/importData"
            },
            pickerOptions: {
                shortcuts: [
                    {
                        text: "最近一周",
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit("pick", [start, end]);
                        },
                    },
                    {
                        text: "最近一个月",
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                            picker.$emit("pick", [start, end]);
                        },
                    },
                    {
                        text: "最近三个月",
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                            picker.$emit("pick", [start, end]);
                        },
                    },
                ],
            },
            user: {},
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            title: "添加",
            open: false,
            tableKey: 0,
            // 遮罩层
            loading: false,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 10,
            // 角色表格数据
            roleList: [],
            // 查询参数
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                placePointName: "",
                goodsName: "",
                status:''
            },
            addForm: {
                phone: "",
                signTime: "",
                description: "",
                imageUrls: [],
                remark: "",
                contactByName: "",
            },
            addRules: {
                goodsId: [
                { required: true, message: "内容不能为空", trigger: "change" },
                ],
                status: [
                { required: true, message: "内容不能为空", trigger: "change" },
                ],
                goodsName: [
                    { required: true, message: "内容不能为空", trigger: "blur" },
                ],
                goodsType: [
                    { required: true, message: "内容不能为空", trigger: "blur" },
                ],
                factoryName: [
                    { required: true, message: "内容不能为空", trigger: "blur" },
                ],
                placePointName: [
                    { required: true, message: "内容不能为空", trigger: "blur" },
                ],
                tel: [
                    { required: true, message: "内容不能为空", trigger: "blur" },
                ],
                address: [
                    { required: true, message: "内容不能为空", trigger: "blur" },
                ],
                // aidProject: [
                //     { required: true, message: "内容不能为空", trigger: "blur" },
                // ],
                foundation: [
                    { required: true, message: "内容不能为空", trigger: "blur" },
                ],
                // aidProjectUrl: [
                //     { required: true, message: "内容不能为空", trigger: "blur" },
                // ],
                // unitPrice: [
                //     { required: true, message: "内容不能为空", trigger: "blur" },
                // ],
                // operateUrl: [
                //     { required: true, message: "内容不能为空", trigger: "blur" },
                // ]
            },
            systemList: [],
        };
    },
    created() {
        this.getListData();
        getUserProfile().then((res) => {
            this.user = res.data;
        });
    },
    methods: {
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
            console.log(file.url);
        },
        // 上传前校检格式和大小
        handleBeforeUpload(file) {
            const type = ["image/jpeg", "image/jpg", "image/png", "image/svg"];
            const isJPG = type.includes(file.type);
            // 检验文件格式
            if (!isJPG) {
                this.$message.error(`图片格式错误!`);
                return false;
            }
            // 校检文件大小
            if (this.fileSize) {
                const isLt = file.size / 1024 < 500;
                if (!isLt) {
                    this.$message.error(`上传文件大小不能超过 500 KB!`);
                    return false;
                }
            }
            return true;
        },
        handleRemove(file, fileList) {
            console.log(file);
            const list = this.addForm.imageUrls.filter(
                (item) => item !== file.response.fileName
            );
            this.addForm.imageUrls = list;
        },
        handleExceed(files, fileList) {
            this.$message.warning(
                `当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length
                } 个文件`
            );
        },
        beforeRemove(file, fileList) {
            return this.$confirm(`确定移除 ${file.name}？`);
        },
        handleUploadSuccess(res, file) {
            // 如果上传成功
            if (res.code == 200) {
                this.addForm.imageUrls.push(res.fileName);
            } else {
                this.$message.error("图片上传失败");
            }
        },
        /** 查询列表 */
        getListData() {
            this.loading = true;
            getList({
                ...this.queryParams
            }).then((response) => {
                this.roleList = response.data.records;
                this.total = response.data.total || 0;
                this.loading = false;
            });
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.$nextTick(() => {
                this.getListData();
            });
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.queryParams.pageNum = 1;
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 添加按钮操作 */
        handleAdd() {
            this.title = "添加";
            this.open = true;
            this.reset();
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            this.title = "编辑";
            console.log(row);
            this.addForm = JSON.parse(JSON.stringify(row))
            this.open = true;
        },
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.addForm = {
                patientIdentity: "",
                patientName: "",
                patientPhone: ""
            };
            this.resetForm("addForm");
        },
        handlePutShop(row){
            let param = JSON.parse(JSON.stringify(row))
            param.status = 1
            putShopData(param).then((res)=>{
                this.$modal.msgSuccess("操作成功");
                this.getListData();
            })
        },
        /** 按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            actionData(ids).then(
                (response) => {
                    this.$modal.msgSuccess("操作成功");
                    this.getListData();
                }
            );
        },
        /** 导入按钮操作 */
        handleImport() {
            this.upload.title = "赠药政策导入";
            this.upload.open = true;
        },
        /** 下载模板操作 */
        importTemplate() {
            this.download('bus/donation/importTemplate', {
            }, `user_template_${new Date().getTime()}.xlsx`)
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true;
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.open = false;
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();
            this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
            this.getList();
        },
        // 提交上传文件
        submitFileForm() {
            this.$refs.upload.submit();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id);
            this.single = selection.length != 1;
            this.multiple = !selection.length;
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["addForm"].validate((valid) => {
                if (valid) {

                    if (this.addForm.id) {
                        editData({
                            ...this.addForm,
                            contactByName: this.user.nickName,
                        }).then((response) => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getListData();
                        });
                    } else {
                        addData({
                            ...this.addForm,
                            contactByName: this.user.nickName,
                        }).then((response) => {
                            this.$modal.msgSuccess("添加成功");
                            this.open = false;
                            this.getListData();
                        });
                    }
                }
            });
        },
    },
};
</script>
<style lang="scss" scoped>
.imgprev {
    width: 100vw;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;

    img {
        max-width: 100%;
        max-height: 100%;
        display: block;
    }
}

.footerForm {
    margin-left: 200px;
}

.formBox {
    width: 600px;
    margin-top: 40px;
}

.btnText {
    color: #0052d9 !important;
}

.dialogForm {
    ::v-deep .el-form-item {
        margin-bottom: 10px;
    }

    ::v-deep.el-form--label-top .el-form-item__label {
        padding: 0;
    }
}

.add {
    background: #0052d9;
    color: #fff;
    border: none;
}

.delBtn {
    background: #e7e7e7;
    color: #000;
    border: none;
}

.open {
    width: 52px;
    height: 32px;
    background: #e3f9e9;
    border-radius: 3px 3px 3px 3px;
    border: 1px solid #2ba471;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 400;
    font-size: 14px;
    color: #2ba471;
}

.close {
    width: 52px;
    height: 32px;
    background: #d8d8d8;
    border-radius: 3px 3px 3px 3px;
    border: 1px solid #767676;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 400;
    font-size: 14px;
    color: #767676;
}

.statusBox {
    width: 100%;
    display: flex;
    justify-content: center;
}

.status_div {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 66px;
    height: 32px;
    background: #ffffff;
    border-radius: 3px;
    border: 1px solid #e7e7e7;
    font-size: 14px;
    background: #f3f3f3;
    color: rgba(0, 0, 0, 0.9);
    line-height: 1;

    &.jxz {
        background: #f2f3ff;
        border: 1px solid #0052d9;
        color: #0052d9;
    }

    &.ywc {
        background: #e3f9e9;
        border: 1px solid #2ba471;
        color: #2ba471;
    }
}

.img {
    width: 38px;
    height: 38px;
}

.img_box {
    display: flex;
    justify-content: center;
    gap: 10px;
}
</style>